<!--
 * @Description: 首页点击影片跳转选择影院
 * @Author: Kerwin
 * @Date: 2025-04-27 17:30:11
 * @LastEditTime: 2025-05-30 12:01:39
 * @LastEditors:  Please set LastEditors
-->
<template>
  <view class="top">
    <!-- 展示影片信息 -->
    <view class="showdy">
      <view class="item">
        <view class="item-l">
          <van-image width="100%" height="232rpx" :src="movieInfo.posterUrl" />
        </view>
        <view class="item-r">
          <view class="nr">
            <view class="bt overwz"> {{ movieInfo.movieName }} </view>
            <view class="xq">
              <view
                >评分：<text style="color: #ff6c18; font-size: 24rpx">{{
                  movieInfo.grade
                }}</text>
              </view>
              <view
                >{{ movieInfo.duration }}分钟 / {{ movieInfo.movieType }}</view
              >
              <view>{{ handleDate(movieInfo.publishDate) }}上映</view>
              <view class="overwz">主演:{{ movieInfo.cast }}</view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view class="text-container" :class="{ expanded: isExpanded }">
      <view class="content" :class="{ collapsed: !isExpanded }">
        简介：{{ movieInfo.intro }}
      </view>
      <view class="toggle-btn" @click="toggleExpand">
        {{ isExpanded ? '收起' : '展开' }}
        <u-icon
          :name="isExpanded ? 'arrow-up' : 'arrow-down'"
          size="14"
        ></u-icon>
      </view>
    </view>
  </view>
  <view style="margin: 20rpx; color: #666">
    <u-button size="mini" @click="getAllCityData" type="success"
      >重新获取城市数据</u-button
    >
  </view>
  <view class="middle">
    <!-- 根据城市和地区搜索 -->
    <view class="ssbox">
      <view>
        <view @click="handleClickArea" class="qybox">
          <view style="width: 200rpx">
            <text>{{ cityName }}</text>
            <u-icon name="arrow-down-fill" size="18" style="margin-left: 5rpx">
            </u-icon>
          </view>
          <view style="width: 200rpx; display: flex">
            <text>{{ regionName }}</text>
            <u-icon
              name="arrow-down-fill"
              size="18"
              style="margin-left: 5rpx"
            ></u-icon>
          </view>
        </view>
        <van-popup :show="showPopup" round position="bottom">
          <u-search
            v-model="searchCity"
            placeholder="搜索城市"
            @input="handleCityInput"
            :show-action="false"
          />
          <van-cascader
            v-model:show="showPopup"
            :options="filteredCityList"
            v-model="cascaderValue"
            @close="handleCloseArea"
            @change="handleChangeArea"
          />
        </van-popup>
      </view>
      <!-- 搜索框 -->
      <view>
        <u-search
          style="width: 350rpx"
          placeholder="请输入影院名称"
          clearabled
          :animation="false"
          :show-action="false"
          v-model="keyword"
          @search="handleSearchCinema"
          @clear="handleClearCinema"
        ></u-search>
      </view>
      <!-- 重新加载图标 -->
      <u-icon
        name="reload"
        size="40"
        @click="getAllCinema(cityId, regionId)"
        style="cursor: pointer"
      ></u-icon>
    </view>
  </view>
  <view class="footer" v-if="showCinemaList.length > 0">
    <view
      class="item"
      v-for="(yy, index) in showCinemaList"
      :key="yy.cinemaId"
      @click="handleGoSelectSession(yy)"
    >
      <view class="item-t overwz"> {{ yy.cinemaName }}</view>
      <view class="item-b">
        <text class="overwz">{{ yy.cinemaAddress }}</text>
        <text>{{ formatDistance(Number(yy.distance)) }}</text>
      </view>
      <view v-if="index == 0" class="tagActive"> 离您最近 </view>
    </view>
    <u-back-top :scroll-top="scrollTop"></u-back-top>
  </view>
</template>

<script lang="ts" setup>
import { ref, computed, watch, nextTick } from 'vue'
import { movieApi } from '@/api'
import {
  onLoad,
  onShow,
  onUnload,
  onReachBottom,
  onPageScroll
} from '@dcloudio/uni-app'
import { useMovieStore } from '@/store/index'
import {
  IMovieInfo,
  ICinemaInfo,
  IArea
} from '@/packageF/components/movieInterface'
import { handleCityData } from '../../components/movieUtil'
const scrollTop = ref(0)
const movieStore = useMovieStore()
// 影片信息
const movieInfo = ref<IMovieInfo>({
  movieName: '',
  grade: '',
  duration: '',
  movieType: '',
  posterUrl: '',
  publishDate: '',
  intro: '',
  cast: '',
  director: '',
  publishStatus: '',
  movieId: ''
})
// 影院原始数据
const cinemaList = ref<ICinemaInfo[]>([
  {
    cinemaAddress: '',
    cinemaId: 0,
    cinemaName: '',
    cinemaPhone: '',
    cityId: 0,
    latitude: 0,
    longitude: 0,
    regionId: 0,
    regionName: '',
    distance: ''
  }
])
// 展示的影院数据
const showCinemaList = ref<ICinemaInfo[]>([
  {
    cinemaAddress: '',
    cinemaId: 0,
    cinemaName: '',
    cinemaPhone: '0',
    cityId: 0,
    latitude: 0,
    longitude: 0,
    regionId: 0,
    regionName: '',
    distance: ''
  }
])
const keyword = ref('')
const isExpanded = ref(false)
const cityName = ref()
const regionName = ref('所有地区')
const cityId = ref()
const regionId = ref()
// 搜索的城市关键字
const searchCity = ref()
// 是否展示选择区域弹框
const showPopup = ref(false)
const cascaderValue = ref()
const cityAndRegionList = ref<IArea[]>([])
const orangeIndex = ref()
onLoad(() => {
  getAllCityData()
})
onShow(() => {
  console.log(
    '影院获取的状态机数据',
    movieStore.xzCityId,
    movieStore.xzCityName
  )
  movieInfo.value = JSON.parse(uni.getStorageSync('movieData'))
  movieInfo.value.movieType = movieInfo.value.movieType.replaceAll('|', ',')
  if (movieStore.xzCityId != 0 && movieStore.xzCityName != '') {
    cityName.value = movieStore.xzCityName
    cityId.value = movieStore.xzCityId
  } else {
    // 兜底位置
    cityName.value = '成都'
    cityId.value = 8
  }
  //复现首页选择的城市的所有地区
  cascaderValue.value = `city_${cityId.value}district_`
  getAllCinema(cityId.value, regionId.value)
})
//页面卸载时清除缓存
onUnload(() => {})

// 监听状态变化
watch(
  () => movieStore.setXzCityId,
  (newValue) => {
    console.log('城市 ID 已更新为:', newValue)
  }
)
watch(cityId, (newValue) => {
  console.log('cityId 变化:', newValue)
})
// 计算属性：根据搜索关键词过滤城市列表
const filteredCityList = computed(() => {
  if (!searchCity.value) return cityAndRegionList.value
  return cityAndRegionList.value.filter((item) =>
    item.cityName.includes(searchCity.value)
  )
})

// 获取所有影院
const getAllCinema = async (cityId: number, regionId: number) => {
  uni.showLoading({ title: '加载中，请稍后', mask: true })
  try {
    const { longitude, latitude } = uni.getStorageSync('currentLocation')
    const { data } = await movieApi
      .getAllCinemaApi({
        cityId,
        regionId,
        longitude,
        latitude
      })
      .finally(() => {
        uni.hideLoading()
      })
    cinemaList.value = data.map((ele: any) => {
      return {
        ...ele,
        distance: ele.distance.toFixed(2) // 保留两位小数
      }
    })
    showCinemaList.value = [...cinemaList.value]
    // console.log('获取距离', cinemaList.value)
  } catch (e) {
    console.log('获取影院error', e)
  }
}
// 获取所有城市数据
const getAllCityData = async () => {
  uni.showLoading({ title: '获取城市数据中，请稍后', mask: true })
  try {
    const { data } = await movieApi.getAllCityAndRegionApi().finally(() => {
      uni.hideLoading()
    })
    cityAndRegionList.value = handleCityData(data)
    // console.log('所有地区数据', handleCityData(data))
  } catch (e) {
    console.log('获取城市error', e)
  }
}
// 点击选择区域
const handleClickArea = () => {
  showPopup.value = true
}
// 关闭选择区域弹框
const handleCloseArea = () => {
  searchCity.value = ''
  showPopup.value = false
}
// 选择区域弹框发生改变
const handleChangeArea = (e: any) => {
  // 获取选中的选项和值
  const { selectedOptions, value } = e
  // 城市赋值
  cityId.value = selectedOptions[0].id
  cityName.value = selectedOptions[0].text
  //将选择的城市id存储在状态机中,用于首页切换
  movieStore.setXzCityId(selectedOptions[0].id)
  movieStore.setXzCityName(selectedOptions[0].text)
  //选择了地区才赋值
  if (selectedOptions.length == 2) {
    regionId.value = selectedOptions[1].id
    regionName.value = selectedOptions[1]?.text
    // 更新状态
    cascaderValue.value = value
  } else {
    // 没有选择默认展示所有
    regionId.value = ''
    regionName.value = '所有地区'
    // 更新状态
    cascaderValue.value = `${value}district_`
  }

  showPopup.value = false
  getAllCinema(cityId.value, regionId.value)
}
// 点击展开或收起
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value
}
// 搜索城市
const handleCityInput = (e: any) => {
  searchCity.value = e
}
// 点击影院去选择场次
const handleGoSelectSession = (cinemaItem: any) => {
  // 找到已选的城市对象
  const findObj = cityAndRegionList.value.find(
    (ele) => ele.cityId == cityId.value
  )
  // console.log('find', findObj)
  const tempObj = {
    province: findObj?.provinceName,
    city: `${findObj?.cityName}市`,
    district: cinemaItem.regionName
  }
  // console.log('temp', tempObj)
  uni.navigateTo({
    url: `/packageF/pages/selectSession/index`
  })
  uni.setStorageSync('dqData', JSON.stringify(tempObj))
  uni.setStorageSync('cinemaData', JSON.stringify(cinemaItem))
  keyword.value = ''
}
// 通过电影名称搜索
const handleSearchCinema = () => {
  showCinemaList.value = cinemaList.value.filter((ele) => {
    return ele.cinemaName.includes(keyword.value)
  })
}
// 搜索影院的清除图标
const handleClearCinema = () => {
  showCinemaList.value = cinemaList.value
}
// 处理日期格式
const handleDate = (date: string) => {
  const [year, monthStr, dayStr] = date.slice(0, 10).split('-')
  const month = parseInt(monthStr, 10)
  const day = parseInt(dayStr, 10)
  // 处理月份和天：小于10时直接显示数字，大于等于10时保持原样
  const formattedMonth = month < 10 ? month : month
  const formattedDay = day < 10 ? day : day
  // 返回格式化后的字符串
  return `${year}年${formattedMonth}月${formattedDay}日`
}
//返回顶部
onPageScroll((e: any) => {
  scrollTop.value = e.scrollTop
})
//公里转换
function formatDistance(km: number): string {
  if (km >= 1) {
    return `${km.toFixed(1)}km`
  } else {
    const meters = km * 1000
    return `${meters.toFixed(1)}m`
  }
}
</script>

<style lang="scss" scoped>
.top {
  background-color: #fff;
  .showdy {
    .item {
      width: 702rpx;
      height: 268rpx;
      background: #ffffff;
      border-radius: 16rpx;
      display: flex;
      align-items: center;
      padding: 0 20rpx;
      .item-l {
        width: 162rpx;
        height: 232rpx;
        border: 1rpx solid #dbdbdbdb;
        border-radius: 5rpx;
        margin-right: 20rpx;
      }
      .item-r {
        flex-grow: 1;
        height: 232rpx;
        display: flex;
        align-items: center;
        font-size: 24rpx;
        .nr {
          height: 100%;
          width: 0rpx;
          flex-grow: 1;
          margin-right: 20rpx;
          .bt {
            font-size: 32rpx;
            color: #000;
            font-weight: bold;
            margin-bottom: 20rpx;
          }
          .xq {
            color: #666666;
            > view {
              margin-bottom: 10rpx;
            }
          }
        }
      }
    }
  }
  .text-container {
    font-size: 24rpx;
    color: #666666;
    max-width: 600px;
    margin: 0px auto;
    padding: 15px;
    border-radius: 8px;
  }
  .content {
    line-height: 1.6;
    margin-bottom: 10px;
  }
  .collapsed {
    display: -webkit-box;
    -webkit-line-clamp: 3; /* 限制显示行数 */
    -webkit-box-orient: vertical;
    overflow: hidden;
    text-overflow: ellipsis;
  }
  .toggle-btn {
    color: #ff6c18;
    cursor: pointer;
    text-align: right;
    align-items: center;
    justify-content: flex-end;
  }
}
.middle {
  background: #fff;
  margin-bottom: 20rpx;
  .ssbox {
    width: 750rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx;
    .qybox {
      width: 300rpx;
      font-size: 24rpx;
      color: #666666;
      display: flex;
      align-items: center;
      flex-grow: 1;
      // justify-content: space-between;
    }
  }
}
.footer {
  // height: 800rpx;
  overflow-y: scroll;
  .item {
    width: 702rpx;
    height: 122rpx;
    background: #ffffff;
    border-radius: 8rpx;
    margin: 0 auto;
    padding: 20rpx;
    margin-bottom: 20rpx;
    position: relative;
    .tagActive {
      position: absolute;
      right: -5rpx;
      top: -10rpx;
      padding: 10rpx;
      //width: 100rpx;
      height: 50rpx;
      line-height: 40rpx;
      color: #fff;
      font-size: 20rpx;
      background-color: #67da8d;
    }
    .item-t {
      color: #000;
      font-size: 28rpx;
      font-weight: bold;
      margin-bottom: 10rpx;
    }
    .item-b {
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 24rpx;
      color: #999;
    }
  }
}
.hswz {
  font-size: 24rpx;
  color: #666;
}
.overwz {
  //   单行文本省略号
  width: 100%;
  white-space: nowrap; /* 禁止文本换行 */
  overflow: hidden; /* 隐藏溢出内容 */
  text-overflow: ellipsis; /* 用省略号表示被截断的文本 */
}
</style>
